package gvalidator

import (
	"errors"
	"github.com/speps/go-hashids/v2"
	"go.uber.org/zap"
	"wzgames/internal/constant"
	"wzgames/pkg/logger"
)

var (
	agentIdHashIds  *hashids.HashID
	gameInstHashIds *hashids.HashID
)

func InitAgentHashIds() error {
	hd := hashids.NewData()
	hd.Salt = constant.AgentIdHashSalt
	hd.MinLength = 10
	h, e := hashids.NewWithData(hd)
	if e != nil {
		logger.Error("[GValidator] init agent id hash ids instance fail", zap.Error(e))
		return e
	}
	agentIdHashIds = h
	return nil
}

func EncodeAgentID(agentId int64) (string, error) {
	if agentIdHashIds != nil {
		return agentIdHashIds.EncodeInt64([]int64{agentId})
	}

	return "", errors.New("agent hash id not init")
}

func DecodeAgentID(agentCode string) (int64, error) {
	if agentIdHashIds != nil {
		v, err := agentIdHashIds.DecodeInt64WithError(agentCode)
		if err != nil {
			//logger.Error("err == ", zap.String("error", err.Error()))
			return 0, err
		}
		return v[0], nil
	}

	return 0, errors.New("agent hash id not init")
}

func InitGameInstHashIds() error {
	hd := hashids.NewData()
	hd.Salt = constant.GameInstHashSalt
	hd.MinLength = 10
	h, e := hashids.NewWithData(hd)
	if e != nil {
		logger.Error("[GValidator] init game instID hash ids instance fail", zap.Error(e))
		return e
	}
	gameInstHashIds = h
	return nil
}

func EncodeGameInstID(instId int64) (string, error) {
	if gameInstHashIds != nil {
		return gameInstHashIds.EncodeInt64([]int64{instId})
	}

	return "", errors.New("game inst hash id not init")
}

func DecodeGameInstID(instCode string) (int64, error) {
	if gameInstHashIds != nil {
		v, err := gameInstHashIds.DecodeInt64WithError(instCode)
		if err != nil {
			//logger.Error("err == ", zap.String("error", err.Error()))
			return 0, err
		}
		return v[0], nil
	}

	return 0, errors.New("game inst hash id not init")
}
